package com.music.note_android.data.repository

import com.music.note_android.data.database.dao.NoteDao
import com.music.note_android.data.model.Note
import kotlinx.coroutines.flow.Flow
import java.io.File
import java.util.UUID
import javax.inject.Inject
import javax.inject.Singleton

/**
 * 笔记数据仓库实现类
 * 实现笔记数据的具体操作逻辑
 */
@Singleton
class NoteRepositoryImpl @Inject constructor(
    private val noteDao: NoteDao
) : NoteRepository {
    
    override fun getAllNotes(): Flow<List<Note>> {
        return noteDao.getAllNotes()
    }
    
    override fun getNotesByFolder(folderId: String): Flow<List<Note>> {
        return noteDao.getNotesByFolderFlow(folderId)
    }
    
    override suspend fun getNoteById(noteId: String): Note? {
        return noteDao.getNoteById(noteId)
    }
    
    override suspend fun searchNotes(query: String): List<Note> {
        return if (query.isBlank()) {
            emptyList()
        } else {
            noteDao.searchNotes(query.trim())
        }
    }
    
    override suspend fun createNote(title: String): Note {
        val currentTime = System.currentTimeMillis()
        val noteId = UUID.randomUUID().toString()
        
        // 创建笔记数据文件路径
        val dataPath = "notes/${noteId}.json"
        
        val note = Note(
            id = noteId,
            title = title.ifBlank { generateDefaultTitle(currentTime) },
            createdTime = currentTime,
            modifiedTime = currentTime,
            folderId = null,
            thumbnailPath = null,
            dataPath = dataPath
        )
        
        noteDao.insertNote(note)
        return note
    }
    
    override suspend fun updateNote(note: Note) {
        val updatedNote = note.copy(modifiedTime = System.currentTimeMillis())
        noteDao.updateNote(updatedNote)
    }
    
    override suspend fun deleteNote(noteId: String) {
        // 获取笔记信息以删除相关文件
        val note = noteDao.getNoteById(noteId)
        note?.let {
            // 删除缩略图文件
            it.thumbnailPath?.let { path ->
                try {
                    File(path).delete()
                } catch (e: Exception) {
                    // 忽略文件删除错误
                }
            }
            
            // 删除笔记数据文件
            try {
                File(it.dataPath).delete()
            } catch (e: Exception) {
                // 忽略文件删除错误
            }
        }
        
        noteDao.deleteNoteById(noteId)
    }
    
    override suspend fun deleteNotes(noteIds: List<String>) {
        // 批量删除相关文件
        noteIds.forEach { noteId ->
            val note = noteDao.getNoteById(noteId)
            note?.let {
                // 删除缩略图文件
                it.thumbnailPath?.let { path ->
                    try {
                        File(path).delete()
                    } catch (e: Exception) {
                        // 忽略文件删除错误
                    }
                }
                
                // 删除笔记数据文件
                try {
                    File(it.dataPath).delete()
                } catch (e: Exception) {
                    // 忽略文件删除错误
                }
            }
        }
        
        noteDao.deleteNotesByIds(noteIds)
    }
    
    override suspend fun renameNote(noteId: String, newTitle: String) {
        val currentTime = System.currentTimeMillis()
        noteDao.updateNoteTitle(noteId, newTitle, currentTime)
    }
    
    override suspend fun moveNoteToFolder(noteId: String, folderId: String?) {
        val currentTime = System.currentTimeMillis()
        noteDao.moveNoteToFolder(noteId, folderId, currentTime)
    }
    
    override suspend fun moveNotesToFolder(noteIds: List<String>, folderId: String?) {
        val currentTime = System.currentTimeMillis()
        noteDao.moveNotesToFolder(noteIds, folderId, currentTime)
    }
    
    override suspend fun updateNoteThumbnail(noteId: String, thumbnailPath: String) {
        val currentTime = System.currentTimeMillis()
        noteDao.updateNoteThumbnail(noteId, thumbnailPath, currentTime)
    }
    
    override suspend fun getNotesCount(): Int {
        return noteDao.getNotesCount()
    }
    
    /**
     * 生成默认标题
     */
    private fun generateDefaultTitle(timestamp: Long): String {
        val calendar = java.util.Calendar.getInstance()
        calendar.timeInMillis = timestamp
        return "笔记 ${calendar.get(java.util.Calendar.YEAR)}-${String.format("%02d", calendar.get(java.util.Calendar.MONTH) + 1)}-${String.format("%02d", calendar.get(java.util.Calendar.DAY_OF_MONTH))} ${String.format("%02d", calendar.get(java.util.Calendar.HOUR_OF_DAY))}:${String.format("%02d", calendar.get(java.util.Calendar.MINUTE))}"
    }
}